#!/usr/bin/python3
#coding=utf-8

import sys
sys.path.append("./")

import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
import json
import time
import allure
from utils.logUtil import logObj

class RequestsUtil:

    def __init__(self):
        retry = Retry(total=3,backoff_factor=0.5)
        self._logObj = logObj
        self._reqObj = requests.Session()
        self._reqObj.mount('https://', HTTPAdapter(max_retries=retry))
        self._reqObj.mount('http://',HTTPAdapter(max_retries=retry))
        self._header = {
            "Content-Type": "application/json",
            "accept": "application/json",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36",
            "Connection": "keep-alive",
        }
        self._token = None
        self._cookie = None
        self.verify = False
        self.timeout = 60
        self.allow_redirects = False

    @property
    def token(self):
        return self._token

    @token.setter
    def token(self, token):
        self._token = token
        if self._token:
            self._header["token"] = self._token
        else:
            if "token" in self._header.keys():
                del self._header["token"]

    @property
    def cookie(self):
        return self._cookie

    @cookie.setter
    def cookie(self, cookie):
        self._cookie = cookie
        if self._cookie:
            self._header["cookie"] = self._cookie
        else:
            if "cookie" in self._header.keys():
                del self._header["cookie"]

    
    def send_request(self, **kwargs):
        """统一发送HTTP请求接口
        Returns:
           res: 调用的API返回的响应对象
        """
        req_header = (
            kwargs.get("headers") if "headers" in kwargs.keys() else self._header
        )
        kwargs["headers"] = req_header
        start_time = time.time()
        res = self._reqObj.request(**kwargs)
        elapsed_time = time.time() - start_time
        with allure.step("HTTP请求"):
            allure.attach(name="url", body=kwargs.get("url"))
            allure.attach(name="method", body=kwargs.get("method"))
            allure.attach(name="headers", body=str(kwargs.get("headers")))
            allure.attach(name="params", body=str(kwargs.get("params")))
            allure.attach(name="data", body=str(kwargs.get("datas")))
            allure.attach(name="json", body=str(kwargs.get("json")))
            allure.attach(name="response", body=str(res.json()))
            allure.attach(name="duration",body=round(elapsed_time,2))
        self._append_request_log(req_header = req_header, response = res, **kwargs)
        return res
    
    def _append_request_log(self, req_header, response, **kwargs):
        """解析http请求的内容并追加到日志文件中
        req_header: 发送请求的header info
        response: 接口响应对象
        """
        req_url = kwargs.get("url") 
        req_method = kwargs.get("method")
        req_headers = req_header
        req_params = kwargs.get("params") if "params" in kwargs.keys() else None
        req_data = kwargs.get("data") if "data" in kwargs.keys() else None
        req_json = kwargs.get("json") if "json" in kwargs.keys() else None
        req_files = kwargs.get("files") if "files" in kwargs.keys() else None
        req_info = {
            "request":{
                "url" : req_url,
                "method": req_method,
                "header": req_headers,
                "params": req_params,
                "data": req_data,
                "json": req_json,
                "files": req_files
            },
            "response":{
                "status_code": response.status_code,
                "res_json": response.json()
            }
        }
        self._logObj.info(req_info)         
        
        
if __name__ == "__main__":
    req = RequestsUtil()
    url = "http://tool.bitefu.net/jiari/"
    params = {
        "d": "2024-02-09",
        "back": "json",
        "info": 1
    }
    method = "post"
    header = {
        "Content-Type": "application/json"
    }
    res = req.send_request(url=url, method = method, params=params)
    print(res.json())
    